import { CheckCircleOutlined, InfoCircleOutlined } from '@ant-design/icons'
import { sleep } from '@gnlab/utils'
import { Button, Alert } from 'antd'
import { colors } from '@/desktop/styles'
import { confirmApiConfig, type CorpDetail } from '../logics/index'

export function APIInfo({ detail }: { detail: CorpDetail }) {
  // true: 检查通过
  // string: 未通过，此为错误信息
  // null: 检查中
  // undefined: 未进行检查
  const [status, setStatus] = useState<true | string | null | undefined>(undefined)

  async function startConfirm() {
    setStatus(null)
    const [res] = await Promise.all([confirmApiConfig(detail.corpIdOrigin), sleep(500)])
    if (res.success) setStatus(true)
    else setStatus(res.error)
  }

  let content: React.ReactNode
  if (status === true) {
    content = <div css={s.success}>
      <div className="info">
        <CheckCircleOutlined />
        <span className="text">检查通过，配置有效！</span>
      </div>
      <Button onClick={startConfirm}>重新检查</Button>
    </div>
  } else if (typeof status === 'string') {
    content = <div css={s.failed}>
      <div className="info">
        <InfoCircleOutlined />
        <div className="text">{status}</div>
      </div>
      <Button onClick={startConfirm}>重新检查</Button>
    </div>
  } else {
    content = <Button loading={status === null} onClick={startConfirm}>
      {status === null ? '检查中' : '检查配置'}
    </Button>
  }
  return <div css={s.apiInfo}>
    <Alert
      className="tips"
      type="info"
      showIcon
      message={
        <>
          若上方“企业信息”填写正确，将自动连通企微官方 API。
          <br />
          连通后，可实现获取联系人数据（unionId、add_way...）等功能。
        </>
      }
    />
    {content}
  </div>
}

const s = {
  apiInfo: css`
    & > .tips {
      align-items: start;
      display: flex;
      margin-bottom: 20px;
      .anticon {
        color: ${colors.link};
        font-size: 18px;
        transform: translateY(2px);
      }
    }
  `,

  tips: css`
    margin-bottom: 20px;
    color: #999;
  `,
  success: css`
    align-items: center;
    column-gap: 15px;
    display: flex;
    .info {
      align-items: center;
      color: ${colors.success};
      display: flex;
    }
    .anticon {
      font-size: 22px;
      margin-right: 8px;
    }
    .text {
      font-size: 15px;
    }
  `,
  failed: css`
    .info {
      align-items: flex-start;
      color: ${colors.warning};
      display: flex;
      margin-bottom: 18px;
    }
    .anticon {
      font-size: 22px;
      margin-right: 8px;
    }
    .text {
      font-size: 15px;
    }
  `,
}
